package com.qmerak.filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.qmerak.common.StringUtil;

/**
 * 
 * 没有和单点认证继承 ， 羡慕先放弃
 * 
 * @author hexin
 * 
 */
public class AuthURLFilter implements Filter {

	private static final Logger LOG = Logger.getLogger(AuthURLFilter.class);
	private static String SPLIT = ";";

	private List<String> ignores = new ArrayList<String>();
	private List<String> ignoresStartWith = new ArrayList<String>();
	private static String LOGIN_PAGE = "/jsp/login.jsp";

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		String reqeustUrl = request.getRequestURI();
		boolean isPermit = false;

		for (String s : ignoresStartWith) {
			if (reqeustUrl.startsWith(s)) {
				isPermit = true;
				break;
			}
		}

		// is not js\images\api
		if (!isPermit) {
			for (String s : ignores) {
				if (reqeustUrl.indexOf(s) >= 0) {
					isPermit = true;
					break;
				}
			}
		}

		HttpSession session = request.getSession();
		Object o = session.getAttribute("");
		if (o != null || isPermit) {
			if (LOG.isDebugEnabled()) {
				if (o != null) {
					// LOG.debug(" request url is " + reqeustUrl);
				}
			}
			chain.doFilter(request, resp);
		} else {
			LOG.debug(reqeustUrl + " is not permit ,need to login page!");
			request.getRequestDispatcher(LOGIN_PAGE).forward(request, resp);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		String ignore = config.getInitParameter("ignore");
		if (StringUtil.isNotBlank(ignore)) {
			String[] tmpIgnores = ignore.split(SPLIT);
			for (String s : tmpIgnores) {
				if (s.contains("*")) {
					ignoresStartWith.add(s.substring(0, s.length() - 1));
				} else {
					ignores.add(s);
				}
			}
		}

		String loginPage = config.getInitParameter("login");
		if (StringUtil.isNotBlank(loginPage)) {
			LOGIN_PAGE = loginPage;
		}
	}
}
